package com.zhao.reggie3.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhao.reggie3.common.R;
import com.zhao.reggie3.damain.Category;
import com.zhao.reggie3.damain.Dish;
import com.zhao.reggie3.damain.DishFlavor;
import com.zhao.reggie3.dto.DishDto;
import com.zhao.reggie3.service.CategoryService;
import com.zhao.reggie3.service.DishFlavorService;
import com.zhao.reggie3.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @description: 菜品控制器
 * @author: zhao
 * @time: 2022/8/19 23:59
 */
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        dishService.savewithflavor(dishDto);

        //清理所有菜品的缓存数据
        //获取所有以dish_xxx开头的key
        Set keys = redisTemplate.keys("dish_*");
        //删除这些key
        redisTemplate.delete(keys);

        /*//清理某个分类下面的菜品缓存数据
        String key  ="dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus();
        //删除这些key
        redisTemplate.delete(key);*/

        return R.success("保存成功");
    }

    @GetMapping("/page")
    @Cacheable(value = "dishCache",key = "'dish_'+#page+'dish_'+#pageSize+'dish_'+#name")
    public R<Page> page(int page,int pageSize,String name){

        Page<Dish> page1 = new Page<>(page,pageSize);
        Page<DishDto> page2 = new Page<>();

        LambdaQueryWrapper<Dish> lqw1 = new LambdaQueryWrapper<>();
        lqw1.like(name!=null,Dish::getName,name);
        lqw1.orderByDesc(Dish::getUpdateTime);

        dishService.page(page1,lqw1);
        //拷贝页面基础信息
        BeanUtils.copyProperties(page1,page2,"records");

        List<Dish> records = page1.getRecords();
        List<DishDto> collect = records.stream().map((dish) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            //分类id
            Long categoryId = dish.getCategoryId();
            //根据分类id查出来的分类对象
            Category byId = categoryService.getById(categoryId);
            //分类对象的名字
            String name1 = byId.getName();
            //设置页面分类名字
            dishDto.setCategoryName(name1);
            return dishDto;
        }).collect(Collectors.toList());

        page2.setRecords(collect);
        return R.success(page2);
    }

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> dishDtoList = null;
        //动态构造key
        String key = "dish_" +dish.getCategoryId()+ "_" + dish.getStatus();
        //先从redis中获取缓存数据
        dishDtoList = (List<DishDto>)redisTemplate.opsForValue().get(key);

        if (dishDtoList!=null){
            //如果存在，直接返回，无需查询数据库
            return R.success(dishDtoList);
        }

        //构造查询条件
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //根据分类id查询菜品信息
        lqw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        lqw.eq(Dish::getStatus,1);
        //添加顺序升序条件和修改时间降序
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //条件查询后返回的菜品集合
        List<Dish> dishlist = dishService.list(lqw);

        dishDtoList = dishlist.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            //获取分类id
            Long categoryId = item.getCategoryId();
            //根据分类id获取分类对象
            Category categorybyId = categoryService.getById(categoryId);
            if (categorybyId!=null){
                //获取分类名字
                String categoryame = categorybyId.getName();
                //设置分类名字展示
                dishDto.setCategoryName(categoryame);
            }

            //获取菜品id
            Long dishid = item.getId();
            //根据菜品id查询口味表
            LambdaQueryWrapper<DishFlavor> lqw1 = new LambdaQueryWrapper<>();
            lqw1.eq(DishFlavor::getDishId, dishid);
            //菜品口味集合
            List<DishFlavor> list = dishFlavorService.list(lqw1);
            //设置口味展示
            dishDto.setFlavors(list);
            return dishDto;
        }).collect(Collectors.toList());

        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到Redis
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updatewithflavor(dishDto);
        //清理所有菜品的缓存数据
        //获取所有以dish_xxx开头的key
        Set keys = redisTemplate.keys("dish_*");
        //删除这些key
        redisTemplate.delete(keys);

        /*//清理某个分类下面的菜品缓存数据
        String key  ="dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus();
        //删除这些key
        redisTemplate.delete(key);*/
        return R.success("修改成功");
    }

}